<?php

use App\Models\Category;

if(!function_exists('categoryTree')){
//    获取分类列表的辅助函数
    /**
     * 所有分类原始数据
     */
    function categoryTree($group = 'goods', $status = false)
    {
        $categorys = Category::select(['id','pid','name','status','level'])
            ->when($status !== false,function ($query) use ($status){
                $query->where('status',$status);
            })
            ->where('group', $group)
            ->where('pid', 0)
            ->with([
                'children' => function ($query) use ($status){
                    $query->select(['id','pid','name','status','level'])
                        ->when($status !== false,function ($query) use ($status){
                            $query->where('status',$status);
                        });
                },
                'children.children' => function ($query) use ($status){
                    $query->select(['id','pid','name','status','level'])
                        ->when($status !== false,function ($query) use ($status){
                        $query->where('status',$status);
                    });
                }
            ])
            ->get();

        return $categorys;
    }

    /**
     * 缓存没被禁用的分类
     */
    if(!function_exists('cache_category')){
        function cache_category(){
            return cache()->rememberForever('cache_category',function (){
                return categoryTree('goods',1);
            });
        }
    }

    /**
     * 缓存所有分类
     */
    if(!function_exists('cache_category_all')){
        function cache_category_all(){
            return cache()->rememberForever('cache_category_all',function (){
                return categoryTree();
            });
        }
    }

    /**
     * 清空分类缓存
     */
    if(!function_exists('forget_cache_category')){
        function forget_cache_category(){
            cache()->forget('cache_category');
            cache()->forget('cache_category_all');
            cache()->forget('cache_menu');
            cache()->forget('cache_menu_all');
        }
    }

    /**
     * 缓存没被禁用的菜单
     */
    if(!function_exists('cache_menu')){
        function cache_menu(){
            return cache()->rememberForever('cache_menu',function (){
                return categoryTree('menu',1);
            });
        }
    }

    /**
     * 缓存所有菜单
     */
    if(!function_exists('cache_menu_all')){
        function cache_menu_all(){
            return cache()->rememberForever('cache_menu_all',function (){
                return categoryTree('menu');
            });
        }
    }
}
